package com.nstar.base.controls
{
	import flash.display.Sprite;
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	
	/**
	 * 监听目标事件
	 * author:zhucm
	 * date:2008.10.20
	 * 
	 * 在监听到目标事件执行完成后向外派发监听完成事件
	 * 可通过监听此完成事件来进行下一步的操作
	 * 
	 * 
	 */ 
	public class EventListener extends Sprite
	{
		public static var LISTEN_COMPLETE:String = "LISTEN_COMPLETE";
		
		private var _source:ArrayCollection ;
		
		public var eventType:String;//监听的目标事件
		
		private static var listener:EventListener;
		
		public function EventListener()
		{
			//TODO: implement function
			super();
		}
		//单例模式
		public static function getInstance():EventListener{
			if (listener==null){
				listener = new EventListener();
			}
			
			return listener;
		}
		
		//添加目标监控对象
		public function addTarget(target:Object,eventType:String):void{
			this.eventType = eventType;
			
			if (_source == null){
				_source = new ArrayCollection();
			}
						
			if (this.eventType !=null && this.eventType!=""){
				target.addEventListener(this.eventType, listen);//监听目标事件	
			}
			
			_source.addItem(target);
			
		}
		
		public function get source():Array{
			return _source.toArray();
		}
		
		//设置目标监控对象源，和addTarget方法同，只是这里一次性添加
		public function set source(value:Array):void{
			_source = new ArrayCollection(value);

			if (eventType !=null && eventType!=""){
				for each(var item:* in _source){
					item.addEventListener(eventType, listen);//监听目标事件
				}
			}
		}
		
		private function listen(event:*):void{
			var index:int = _source.getItemIndex(event.target);
			if (index!=-1){
				_source.removeItemAt(index);	
			}
			if (_source == null || _source.length == 0){
				this.dispatchEvent(new Event(LISTEN_COMPLETE));//监听完成后向外通知
			}
		}

	}
}